package io.kiki.task.client.common.init;

import io.kiki.task.client.common.Lifecycle;
import io.kiki.task.client.common.event.ClientStartedEvent;
import io.kiki.task.client.common.event.ClientStartingEvent;
import io.kiki.task.common.core.context.SpringContext;
import io.kiki.task.common.core.util.JobVersion;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 系统启动监听器
 *
 * @author huihui
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ApplicationRunner implements org.springframework.boot.ApplicationRunner {
    private final List<Lifecycle> lifecycleList;
    private volatile boolean isStarted = false;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        if (isStarted) {
            log.info("kiki.task client already started v{}", JobVersion.getVersion());
            return;
        }


        log.info("kiki.task client is preparing to start... v{}", JobVersion.getVersion());
        SpringContext.getContext().publishEvent(new ClientStartingEvent());
        lifecycleList.forEach(Lifecycle::start);
        SpringContext.getContext().publishEvent(new ClientStartedEvent());
        isStarted = true;
        log.info("kiki.task client started successfully v{}", JobVersion.getVersion());
    }

}
